package dao.impl;

import dao.BaseDao;
import dao.UserDao;
import entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImpl extends BaseDao implements UserDao {
    Connection conn;
    PreparedStatement pstmt;
    ResultSet rs;

    @Override
    public int insertUser(User user) {
        int r = 0;
        String sql = "INSERT INTO `timesequence`.`user` (`uno`, `uname`, `pwd`, `sex`,`photo`) VALUES (?, ?, ?, ?,?)";
        conn = getConnection();
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,user.getUno());
            pstmt.setString(2,user.getUname());
            pstmt.setString(3,user.getPwd());
            pstmt.setString(4,user.getSex());
            if (user.getSex().equals("男"))
                pstmt.setString(5,"http://m.qpic.cn/psc?/V125C4nA0idrYe/ruAMsa53pVQWN7FLK88i5nRx82xFLXWviZud784sg9KjMjiQ8AqIzMlM0IahbFy66hIwDlZZiSZMreiIUOeXm19QDPyBQWOviNU3N61mmw8!/mnull&bo=yADIAAAAAAADByI!&rf=photolist&t=5");
            else
                pstmt.setString(5,"http://m.qpic.cn/psc?/V125C4nA0idrYe/ruAMsa53pVQWN7FLK88i5nRx82xFLXWviZud784sg9KXBYj5etYEN348V2MfUODw9wH*Dx0CLNKQHj0mePpdoMf*KeMqPDyQHggenQwQPp8!/mnull&bo=yADIAAAAAAADByI!&rf=photolist&t=5");
            r = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            closeAll(conn,pstmt,null);
        }
        return r;
    }

    @Override
    public int selectUNo(String uno) {
        int r = 0;
        String sql = "SELECT COUNT(uno) FROM `user` WHERE uno = ?;";
        conn = getConnection();
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,uno);
            rs = pstmt.executeQuery();
            if (rs.next()){
                r = rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return r;
    }

    @Override
    public ResultSet selectUser(int uid) {
        String sql = "SELECT * FROM `user` WHERE uid = ?;";
        conn = getConnection();
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1,uid);
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    @Override
    public ResultSet selectUser(String uno, String pwd) {
        String sql = "SELECT * FROM `user` WHERE uno = ? and pwd = ?;";
        conn = getConnection();
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,uno);
            pstmt.setString(2,pwd);
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
}
